package org.lmj.registry;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.lmj.constant.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ServiceRegistry {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class);

    private CountDownLatch latch = new CountDownLatch(1);

    private String registryAddress;

    public ServiceRegistry(String registryAddress) {
        this.registryAddress = registryAddress;
    }

    public void register(String data) {

        if (data != null) {
            ZooKeeper zk = connectServer();
            if (zk != null) {
                System.out.println("zookeeper=========要添加的节点数据"+data);
                //createNode(zk, data);
                /**
                 *  AddRootNode(zk); // Add root node if not exist
                 *  createNode(zk, data);
                 * ========================================================================================================
                 * 这里在原文的基础上加了AddRootNode()判断服务父节点是否存在，如果不存在则添加一个PERSISTENT的服务父节点，这样虽然启动服务时多了点判断，但是不需要手动命令添加服务父节点了。
                 *
                 * 关于Zookeeper的使用原理，可以看这里《ZooKeeper基本原理》。下面是链接
                 * https://www.cnblogs.com/luxiaoxun/p/4887452.html
                 */
                setNode(zk, data);
                try {
                    zk.getData(Constant.ZK_DATA_PATH,true,null);
                    System.out.println(new String(zk.getData(Constant.ZK_DATA_PATH,true,null))+"===获取服务注册的信息");
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private ZooKeeper connectServer() {
        ZooKeeper zk = null;
       // try {

            try {
                zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
                    @Override
                    public void process(WatchedEvent watchedEvent) {
                        System.out.println(registryAddress + "zookeeper监听到有客户端连上来了，所以节点watcher发生了变化===serviceRegistry.java========404040404");
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
            // zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
          /*  zk = new ZooKeeper("192.168.3.200:2181", Constant.ZK_SESSION_TIMEOUT, new Watcher() {

                @Override
                public void process(WatchedEvent event) {
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }else {
                        System.out.println(Event.KeeperState.SyncConnected+"============454545454554"+event.getState());
                    }
                }
            });*/
            //latch.await();
//        } catch (IOException | InterruptedException e) {
//            LOGGER.error("", e);
//        }
            return zk;
        }

    private void setNode(ZooKeeper zk, String data) {
        try {
            byte[] bytes = data.getBytes();
            /**
             * // 从未修改后的话版本号为0，修改成功后版本号递增1
             *             int version = 0;
             */
            String path = String.valueOf(zk.setData(Constant.ZK_DATA_PATH, bytes, -1));
            LOGGER.debug("create zookeeper node ({} => {})", path, data);
        } catch (KeeperException | InterruptedException e) {
            LOGGER.error("", e);
        }
    }
}